package van.planifolia.demo01;

import java.lang.reflect.Field;

/**
 * Created by Intellij IDEA<br>
 * 反射操作指定类的属性信息
 * @author Planifolia.Van
 * @version 1.0
 * @date 2022/10/27 16:51
 */
public class ReflexOperationFields {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        // 分别创建实例对象与反射对象
        Pig pig = new Pig("120KG","彼阁");
        Class<? extends Pig> aClass = pig.getClass();
        // 获取Pig类的字段weight
        Field weight = aClass.getDeclaredField("weight");
        // 获取Pig类的字段name
        Field name = aClass.getDeclaredField("name");
        // 开启允许操作私有属性的权限
        weight.setAccessible(true);
        name.setAccessible(true);

        // 获取pig对象的属性weight
        System.out.println(weight.get(pig));
        // 设置pig对象的属性name
        name.set(pig,"pig");

        //最后打印查看结果
        System.out.println(pig);
    }
}
class Pig{
    private String weight;
    private String name;

    public Pig(String weight, String name) {
        this.weight = weight;
        this.name = name;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Pig{" +
                "weight='" + weight + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}